<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-sitemap"></i>
              动态菜单管理
            </h1>
            <p class="page-subtitle">可视化创建和管理系统菜单，支持拖拽排序和自动生成页面</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ totalMenuCount || 0 }}</div>
              <div class="stat-label">菜单总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ generatedCount || 0 }}</div>
              <div class="stat-label">自动生成</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ iconCount || 0 }}</div>
              <div class="stat-label">可用图标</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="search-filters glass-effect">
        <el-form inline class="search-form">
          <el-form-item>

            <el-button @click="refreshMenuTree" class="glass-button refresh-button" :loading="treeLoading">
              <i class="fa fa-refresh"></i>
              刷新菜单
            </el-button>
            <el-button @click="showIcons" class="glass-button add-button">
              <i class="fa fa-picture-o"></i>
              查看图标
            </el-button>
            <el-button @click="showCreateDialog = true" class="glass-button create-button">
              <i class="fa fa-plus"></i>
              创建菜单
            </el-button>
            <el-button @click="forceRefreshPage" class="glass-button refresh-button">
              <i class="fa fa-refresh"></i>
              强制刷新导航栏
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 左右分栏布局 -->
      <div class="main-layout">
        <!-- 左侧：菜单编辑器 -->
        <div class="left-panel audit-table-section glass-effect">
          <div class="section-title">
            <i class="fa fa-edit"></i>
            菜单编辑器
          </div>

          <div v-if="menuTree.length === 0" class="empty-state">
            <p>暂无菜单数据，点击"刷新菜单"按钮加载数据</p>
          </div>
          <div v-else class="menu-editor">
            <!-- 菜单树形结构 -->
            <el-tree
              ref="menuTreeRef"
              :data="menuTree"
              :props="treeProps"
              node-key="id"
              :default-expand-all="true"
              :expand-on-click-node="false"
              draggable
              @node-drop="handleNodeDrop"
              @node-click="handleNodeClick"
              class="menu-tree"
            >
              <template #default="{ node, data }">
                <div class="tree-node" :class="{ 'level-1': !data.parent_id, 'level-2': !!data.parent_id }">
                  <div class="node-content" @click="handleNodeContentClick(node, data)">
                    <div class="node-main-info">
                      <div class="node-level-indicator">
                        <el-tag v-if="!data.parent_id" size="small" type="primary" class="level-tag">一级菜单</el-tag>
                        <el-tag v-else size="small" type="warning" class="level-tag">二级菜单</el-tag>
                      </div>
                      <i :class="getIconClass(data.icon)" class="node-icon"></i>
                      <span class="node-label">{{ data.name }}</span>
                      <el-tag v-if="data.is_generated" size="small" type="success" class="generated-tag">自动生成</el-tag>
                      <span class="node-path">{{ data.path }}</span>
                    </div>
                    <div v-if="data.parent_id" class="node-parent-info">
                      <span class="parent-info">父级菜单: {{ getParentName(data.parent_id) }}</span>
                    </div>
                  </div>
                  <div class="node-actions">
                    <el-button size="small" link @click.stop="editMenu(data)" class="action-glass-button">
                      <i class="fa fa-edit"></i>
                    </el-button>
                    <el-button size="small" link @click.stop="deleteMenu(data)" class="action-glass-button">
                      <i class="fa fa-trash"></i>
                    </el-button>
                    <el-button v-if="data.is_generated" size="small" link @click.stop="openGeneratedPage(data)" class="action-glass-button">
                      <i class="fa fa-eye"></i>
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>

        <!-- 右侧：菜单预览 -->
        <div class="right-panel audit-table-section glass-effect">
          <div class="section-title">
            <i class="fa fa-eye"></i>
            导航栏预览
          </div>

          <div class="menu-preview">
            <div class="preview-sidebar">
              <div class="preview-logo">
                <i class="fa fa-rocket"></i>
                <span>DevOps系统</span>
              </div>

              <div class="preview-menu">
                <div v-for="menu in menuTree" :key="menu.id" class="preview-menu-item">
                  <!-- 一级菜单 -->
                  <div v-if="!menu.children || menu.children.length === 0" class="preview-item">
                    <i :class="getIconClass(menu.icon)" class="preview-icon"></i>
                    <span class="preview-text">{{ menu.name }}</span>
                  </div>

                  <!-- 有子菜单的一级菜单 -->
                  <div v-else class="preview-submenu">
                    <div class="preview-parent">
                      <i :class="getIconClass(menu.icon)" class="preview-icon"></i>
                      <span class="preview-text">{{ menu.name }}</span>
                      <i class="fa fa-angle-down preview-arrow"></i>
                    </div>
                    <div class="preview-children">
                      <div v-for="child in menu.children" :key="child.id" class="preview-child">
                        <i :class="getIconClass(child.icon)" class="preview-child-icon"></i>
                        <span class="preview-child-text">{{ child.name }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>


        </div>
      </div>
    </div>

    <!-- 创建菜单对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建新菜单"
      width="600px"
      class="create-dialog"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="100px"
        class="create-form"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入菜单名称，如：用户管理" />
        </el-form-item>

        <el-form-item label="父级菜单" prop="parent_id">
          <el-select v-model="createForm.parent_id" placeholder="选择父级菜单（留空为一级菜单）" clearable>
            <el-option label="无（创建一级菜单）" :value="null" />
            <el-option
              v-for="menu in parentMenuOptions"
              :key="menu.id"
              :label="menu.name"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择图标" prop="icon">
          <div class="icon-selector">
            <el-input
              v-model="createForm.icon"
              placeholder="选择图标"
              readonly
              class="icon-input"
            >
              <template #prefix>
                <i v-if="createForm.icon" :class="createForm.icon" class="selected-icon"></i>
              </template>
              <template #suffix>
                <el-button link @click="showIconSelector = true">
                  <i class="fa fa-search"></i>
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>

        <el-form-item label="菜单描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜单功能描述"
          />
        </el-form-item>

        <el-form-item label="生成页面" prop="generate_page">
          <el-radio-group v-model="createForm.generate_page">
            <el-radio :label="true">是，生成对应的页面文件</el-radio>
            <el-radio :label="false">否，仅创建菜单项</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <i class="fa fa-info-circle"></i>
            <span v-if="createForm.parent_id">二级菜单建议生成页面文件</span>
            <span v-else>一级菜单可选择是否生成页面，通常作为分组使用</span>
          </div>
        </el-form-item>

        <!-- 预览区域 -->
        <el-form-item label="路径预览" v-if="createForm.generate_page">
          <div class="preview-info">
            <div class="preview-item">
              <label>生成路径：</label>
              <code>{{ previewPath }}</code>
            </div>
            <div class="preview-item">
              <label>组件名：</label>
              <code>{{ previewComponent }}</code>
            </div>
            <div class="preview-item">
              <label>文件路径：</label>
              <code>{{ previewFilePath }}</code>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false" class="glass-button">取消</el-button>
          <el-button @click="handleCreateMenu" :loading="creating" class="glass-button create-button">
            {{ creating ? '创建中...' : '创建菜单' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog
      v-model="showIconSelector"
      title="选择图标"
      width="800px"
      class="icon-selector-dialog"
    >
      <div class="icon-search">
        <el-input
          v-model="iconSearchText"
          placeholder="搜索图标..."
          clearable
          prefix-icon="fa fa-search"
        />
      </div>
      <div class="icon-grid">
        <div
          v-for="icon in filteredIcons"
          :key="icon"
          class="icon-item"
          :class="{ active: createForm.icon === icon }"
          @click="selectIcon(icon)"
        >
          <i :class="icon" class="icon-preview"></i>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showIconSelector = false" class="glass-button">取消</el-button>
          <el-button @click="confirmIconSelection" :disabled="!createForm.icon" class="glass-button create-button">
            确定选择
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图标展示对话框 -->
    <el-dialog
      v-model="showIconDialog"
      title="可用图标列表"
      width="800px"
      class="icon-dialog"
    >
      <div class="icon-grid">
        <div v-for="icon in availableIcons" :key="icon" class="icon-item">
          <i :class="icon" class="icon-preview"></i>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dynamicMenuApi } from '@/api/dynamicMenu'
import { useMenuStore } from '@/stores/menu'

// Store
const menuStore = useMenuStore()

// 响应式数据
const menuTree = ref([])
const treeLoading = ref(false)

const showIconDialog = ref(false)
const showCreateDialog = ref(false)
const showIconSelector = ref(false)
const availableIcons = ref([])
const generatedCount = ref(0)
const iconCount = ref(0)
const creating = ref(false)
const createFormRef = ref(null)
const iconSearchText = ref('')
const menuTreeRef = ref(null)
const selectedMenu = ref(null)

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 创建菜单表单
const createForm = reactive({
  name: '',
  parent_id: null,
  icon: 'fa-file',
  description: '',
  generate_page: true
})

// 表单验证规则
const createRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ]
}

// 计算属性
const previewPath = computed(() => {
  if (!createForm.name) return '/your-menu-path'

  // 简单的中文转英文映射
  const chineseToEnglish = {
    '管理': 'management',
    '系统': 'system',
    '用户': 'user',
    '主机': 'host',
    '服务': 'service',
    '配置': 'config',
    '监控': 'monitor',
    '日志': 'log',
    '审计': 'audit',
    '权限': 'permission',
    '角色': 'role',
    '组': 'group',
    '菜单': 'menu',
    '设置': 'settings',
    '数据': 'data',
    '文件': 'file',
    '网络': 'network',
    '安全': 'security',
    '备份': 'backup',
    '报表': 'report',
    '任务': 'task',
    '项目': 'project',
    '资源': 'resource',
    '库存': 'inventory',
    '订单': 'order',
    '财务': 'finance'
  }

  let englishName = createForm.name
  Object.entries(chineseToEnglish).forEach(([chinese, english]) => {
    englishName = englishName.replace(new RegExp(chinese, 'g'), english)
  })

  // 移除非字母数字字符，转换为小写，用连字符连接
  englishName = englishName
    .replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '-')
    .replace(/[\u4e00-\u9fff]/g, '')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
    .toLowerCase() || 'custom-page'

  return `/${englishName}`
})

const previewComponent = computed(() => {
  if (!createForm.name) return 'YourMenuComponent'

  const path = previewPath.value.replace(/^\//, '').replace(/\//g, '-')
  return path.split('-').map(word =>
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join('')
})

const previewFilePath = computed(() => {
  if (!createForm.name || !createForm.generate_page) return ''

  const component = previewComponent.value
  if (createForm.parent_id) {
    // 二级菜单
    const parentMenu = parentMenuOptions.value.find(menu => menu.id === createForm.parent_id)
    const parentPath = parentMenu ? parentMenu.name.toLowerCase().replace(/\s+/g, '-') : 'unknown'
    return `src/views/${parentPath}/${component}.vue`
  } else {
    // 一级菜单
    return `src/views/${component}.vue`
  }
})

const filteredIcons = computed(() => {
  if (!iconSearchText.value) return availableIcons.value

  const search = iconSearchText.value.toLowerCase()
  return availableIcons.value.filter(icon =>
    icon.toLowerCase().includes(search)
  )
})

const parentMenuOptions = computed(() => {
  // 只返回一级菜单作为父级选项
  return menuTree.value.filter(menu => !menu.parent_id)
})

const totalMenuCount = computed(() => {
  const countAllMenus = (menus: any[]): number => {
    let count = 0
    menus.forEach(menu => {
      count++ // 计算当前菜单
      if (menu.children && menu.children.length > 0) {
        count += countAllMenus(menu.children) // 递归计算子菜单
      }
    })
    return count
  }
  return countAllMenus(menuTree.value)
})

// 方法
const refreshMenuTree = async () => {
  treeLoading.value = true
  try {
    const response = await dynamicMenuApi.getMenuTree()
    if (response.success) {
      menuTree.value = response.data

      // 计算统计数据
      generatedCount.value = countGeneratedMenus(response.data)

      ElMessage.success('菜单数据加载成功')
    } else {
      ElMessage.error(response.message || '获取菜单树失败')
    }
  } catch (error) {
    console.error('获取菜单树失败:', error)
    ElMessage.error('获取菜单树失败')
  } finally {
    treeLoading.value = false
  }
}



const showIcons = async () => {
  if (availableIcons.value.length === 0) {
    try {
      const response = await dynamicMenuApi.getAvailableIcons()
      if (response.success) {
        availableIcons.value = response.data
        iconCount.value = response.data.length
      }
    } catch (error) {
      ElMessage.error('获取图标列表失败')
      return
    }
  }
  showIconDialog.value = true
}

const openGeneratedPage = (menu: any) => {
  if (menu.path) {
    const url = `${window.location.origin}${menu.path}`
    window.open(url, '_blank')
  } else {
    ElMessage.warning('该菜单没有设置路径')
  }
}

const countGeneratedMenus = (menus: any[]): number => {
  let count = 0
  menus.forEach(menu => {
    if (menu.is_generated) count++
    if (menu.children && menu.children.length > 0) {
      count += countGeneratedMenus(menu.children)
    }
  })
  return count
}

const handleCreateMenu = async () => {
  if (!createFormRef.value) return

  try {
    const valid = await createFormRef.value.validate()
    if (!valid) return

    creating.value = true

    const response = await dynamicMenuApi.createMenu({
      name: createForm.name,
      parent_id: createForm.parent_id,
      icon: createForm.icon,
      description: createForm.description,
      generate_page: createForm.generate_page,
      // 传递前端计算好的英文路径和组件名
      english_path: previewPath.value.replace(/^\//, ''),
      english_component: previewComponent.value
    })

    if (response.success) {
      ElMessage.success('菜单创建成功！')
      showCreateDialog.value = false
      resetCreateForm()
      await refreshMenuTree()
      // 刷新导航栏菜单
      await refreshNavigationMenu()
    } else {
      ElMessage.error(response.message || '创建菜单失败')
    }
  } catch (error) {
    console.error('创建菜单失败:', error)
    ElMessage.error('创建菜单失败')
  } finally {
    creating.value = false
  }
}

const resetCreateForm = () => {
  if (createFormRef.value) {
    createFormRef.value.resetFields()
  }
  Object.assign(createForm, {
    name: '',
    parent_id: null,
    icon: 'fa-file',
    description: '',
    generate_page: true
  })
}

const selectIcon = (icon: string) => {
  createForm.icon = icon
}

const confirmIconSelection = () => {
  showIconSelector.value = false
}

const forceRefreshPage = () => {
  ElMessageBox.confirm(
    '这将刷新整个页面以更新导航栏菜单，确定继续吗？',
    '确认刷新',
    {
      confirmButtonText: '确定刷新',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 刷新页面
    window.location.reload()
  }).catch(() => {
    // 用户取消
  })
}

const getIconClass = (icon: string) => {
  if (!icon) return 'fa fa-file'

  // 如果已经包含fa前缀，直接返回
  if (icon.startsWith('fa ')) {
    return icon
  }

  // 如果是fa-开头，添加fa前缀
  if (icon.startsWith('fa-')) {
    return `fa ${icon}`
  }

  // 特殊处理一些图标
  const iconMap = {
    'fa-test': 'fa fa-flask',
    'fa-file-code-o': 'fa fa-file-code-o',
    'fa-history': 'fa fa-history',
    'fa-line-chart': 'fa fa-line-chart'
  }

  if (iconMap[icon]) {
    return iconMap[icon]
  }

  // 如果没有fa前缀，添加
  return `fa ${icon}`
}

const refreshNavigationMenu = async () => {
  try {
    console.log('🔄 开始同步菜单配置文件...')

    // 显示加载提示
    const loadingMessage = ElMessage({
      message: '正在同步菜单配置，请稍候...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    // 调用后端API同步静态配置文件
    const response = await fetch('/api/dynamic-menus/full_sync/', {
      method: 'POST',
      headers: {
        'Authorization': `Token ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    // 关闭加载提示
    loadingMessage.close()

    if (result.success) {
      console.log('✅ 静态配置同步成功:', result)

      // 显示成功提示
      ElMessage({
        message: result.message || '菜单配置已同步，页面将自动刷新',
        type: 'success',
        duration: 2000,
        showClose: true
      })

      // 延迟刷新页面以应用新配置
      setTimeout(() => {
        window.location.reload()
      }, 2000)

    } else {
      console.error('❌ 静态配置同步失败:', result.message)
      ElMessage({
        message: `同步失败: ${result.message}`,
        type: 'error',
        duration: 5000,
        showClose: true
      })
    }

  } catch (error) {
    console.error('❌ 菜单同步请求失败:', error)

    ElMessage({
      message: '菜单同步请求失败，请检查网络连接或联系管理员',
      type: 'error',
      duration: 5000,
      showClose: true
    })
  }
}

const getParentName = (parentId: number) => {
  if (!parentId) return ''

  // 创建一个扁平化的菜单映射，包含所有菜单项
  const flatMenuMap = new Map()

  const flattenMenus = (menus: any[]) => {
    menus.forEach(menu => {
      flatMenuMap.set(menu.id, menu.name)
      if (menu.children && menu.children.length > 0) {
        flattenMenus(menu.children)
      }
    })
  }

  // 扁平化当前菜单树
  flattenMenus(menuTree.value)

  // 查找父级菜单名称
  const parentName = flatMenuMap.get(parentId)
  return parentName || '未知'
}

const handleNodeClick = (data: any) => {
  selectedMenu.value = data
  console.log('选中菜单:', data)
}

const handleNodeContentClick = (node: any, data: any) => {
  // 如果是一级菜单且有子菜单，则展开/折叠
  if (!data.parent_id && data.children && data.children.length > 0) {
    node.expanded = !node.expanded
  }
  // 选中菜单
  selectedMenu.value = data
}

const handleNodeDrop = async (draggingNode: any, dropNode: any, dropType: string) => {
  try {
    console.log('拖拽菜单:', draggingNode.data.name, '到', dropNode.data.name, '位置:', dropType)

    // 构建新的排序数据
    const menuOrders = []

    const buildOrderData = (nodes: any[], parentId: any = null, startWeight = 1) => {
      nodes.forEach((node, index) => {
        const weight = startWeight + index
        menuOrders.push({
          id: node.data.id,
          sort_weight: weight,
          parent_id: parentId
        })

        if (node.children && node.children.length > 0) {
          buildOrderData(node.children, node.data.id, weight * 100)
        }
      })
    }

    // 获取树的根节点
    const rootNodes = menuTreeRef.value?.store.root.childNodes || []
    buildOrderData(rootNodes)

    // 发送排序请求
    const response = await dynamicMenuApi.reorderMenus(menuOrders)
    if (response.success) {
      ElMessage.success('菜单排序已保存')
      await refreshMenuTree()
      // 简单排序不需要重新生成配置文件，只刷新菜单树
      // await refreshNavigationMenu()
    } else {
      ElMessage.error(response.message || '保存排序失败')
      await refreshMenuTree() // 恢复原始状态
    }
  } catch (error) {
    console.error('保存菜单排序失败:', error)
    ElMessage.error('保存菜单排序失败')
    await refreshMenuTree() // 恢复原始状态
  }
}

const editMenu = (menu: any) => {
  console.log('编辑菜单:', menu)
  // TODO: 实现编辑功能
  ElMessage.info('编辑功能开发中...')
}

const deleteMenu = async (menu: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.name}" 吗？${menu.is_generated ? '这将同时删除自动生成的页面文件。' : ''}`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await dynamicMenuApi.deleteMenuWithComponent(menu.id)
    if (response.success) {
      ElMessage.success('菜单删除成功')
      await refreshMenuTree()
      // 刷新导航栏菜单
      await refreshNavigationMenu()
      if (selectedMenu.value?.id === menu.id) {
        selectedMenu.value = null
      }
    } else {
      ElMessage.error(response.message || '删除菜单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败')
    }
  }
}

// 生命周期
onMounted(async () => {
  // 页面加载时自动获取菜单数据
  await refreshMenuTree()

  // 同时获取图标列表
  try {
    const response = await dynamicMenuApi.getAvailableIcons()
    if (response.success) {
      availableIcons.value = response.data
      iconCount.value = response.data.length
    }
  } catch (error) {
    console.error('获取图标列表失败:', error)
  }
})
</script>

<style lang="scss" scoped>
/* 使用Ansible配置页面的样式 */

/* 星空背景动画 */
.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -999;
  background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 50%, #16213e 100%);
  overflow: hidden;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
  pointer-events: none;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 160px 30px, #ddd, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite;
  opacity: 0.5;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 80px 10px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 120px 50px, #eee, transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 10s infinite;
  opacity: 0.3;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, #fff, transparent),
    radial-gradient(1px 1px at 150px 150px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 250px 250px;
  animation: zoom 15s infinite;
  opacity: 0.2;
}

@keyframes zoom {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

/* 主容器 */
.ansible-audit-container {
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
  background: transparent;
}

.audit-content {
  position: relative;
  z-index: 1;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 玻璃效果 */
.glass-effect {
  backdrop-filter: blur(20px);
  background: rgba(164, 244, 186, 0.08);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

/* 页面头部 */
.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section {
  flex: 1;
}

.page-title {
  color: #00eaff;
  font-size: 2.5em;
  margin: 0 0 10px 0;
  text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  display: flex;
  align-items: center;
  gap: 15px;

  i {
    font-size: 0.8em;
  }
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.8);
  font-size: 1.1em;
  margin: 0;
  line-height: 1.5;
}

/* 统计卡片 */
.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-5px);
    box-shadow:
      0 12px 40px rgba(0, 0, 0, 0.4),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
  }
}

.stat-number {
  font-size: 2.2em;
  font-weight: bold;
  color: #00eaff;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
  margin-bottom: 5px;
}

.stat-label {
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9em;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 搜索过滤器 */
.search-filters {
  margin-bottom: 30px;
  padding: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 15px;
}

/* 表格区域 */
.audit-table-section {
  margin-bottom: 30px;
  padding: 30px;
}

.section-title {
  color: #00eaff;
  font-size: 1.3em;
  margin-bottom: 20px;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 主布局 */
.main-layout {
  display: flex;
  gap: 30px;
  min-height: 600px;
}

.left-panel {
  flex: 1;
  min-width: 400px;
}

.right-panel {
  flex: 1;
  min-width: 400px;

  .section-content {
    min-height: auto;
    max-height: none;
    height: auto;
    overflow: visible;

    /* 隐藏滚动条但保持滚动功能 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */

    &::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera */
    }
  }
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 1.1em;
}

/* 菜单编辑器 */
.menu-editor {
  padding: 20px;
}

.menu-tree {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

/* 树形节点样式 */
.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 16px;
  position: relative;

  &.level-1 {
    .node-content {
      background: linear-gradient(135deg, rgba(0, 234, 255, 0.08) 0%, rgba(0, 234, 255, 0.03) 100%);
      border: 1px solid rgba(0, 234, 255, 0.2);
      border-left: 4px solid #00eaff;
      box-shadow: 0 2px 8px rgba(0, 234, 255, 0.1);
    }
  }

  &.level-2 {
    margin-left: 50px;

    .node-content {
      background: linear-gradient(135deg, rgba(255, 193, 7, 0.08) 0%, rgba(255, 193, 7, 0.03) 100%);
      border: 1px solid rgba(255, 193, 7, 0.2);
      border-left: 4px solid #ffc107;
      box-shadow: 0 2px 8px rgba(255, 193, 7, 0.1);
    }
  }

  .node-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
    flex: 1;
    padding: 16px;
    border-radius: 8px;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
    min-height: 60px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 234, 255, 0.2);
    }

    .node-main-info {
      display: flex;
      align-items: center;
      gap: 12px;
      width: 100%;
    }

    .node-parent-info {
      margin-top: 4px;
      padding-left: 8px;
    }

    .node-level-indicator {
      flex-shrink: 0;

      .level-tag {
        font-weight: 600;
        font-size: 11px;
        padding: 4px 8px;
        border-radius: 12px;
      }
    }

    .node-icon {
      color: #00eaff;
      width: 18px;
      font-size: 16px;
      flex-shrink: 0;
      text-shadow: 0 0 5px rgba(0, 234, 255, 0.3);
    }

    .node-label {
      color: rgba(255, 255, 255, 0.95);
      font-weight: 600;
      font-size: 14px;
      flex-shrink: 0;
      min-width: 100px;
    }

    .generated-tag {
      font-size: 10px;
      padding: 2px 6px;
      border-radius: 8px;
      flex-shrink: 0;
    }

    .node-path {
      color: rgba(255, 255, 255, 0.6);
      font-size: 11px;
      font-family: 'Courier New', monospace;
      background: rgba(0, 0, 0, 0.3);
      padding: 4px 8px;
      border-radius: 4px;
      flex-shrink: 0;
      border: 1px solid rgba(255, 255, 255, 0.1);
      margin-left: auto;
    }

    .parent-info {
      color: rgba(255, 255, 255, 0.6);
      font-size: 12px;
      font-style: italic;
      background: rgba(0, 0, 0, 0.2);
      padding: 4px 8px;
      border-radius: 4px;
      border: 1px solid rgba(255, 255, 255, 0.1);
      display: inline-block;
    }
  }

  .node-actions {
    display: flex;
    gap: 6px;
    opacity: 0;
    transition: all 0.3s ease;
    margin-left: 12px;
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(0, 0, 0, 0.5);
    padding: 4px 8px;
    border-radius: 6px;
    backdrop-filter: blur(10px);
  }

  &:hover .node-actions {
    opacity: 1;
  }
}

/* 菜单预览 */
.menu-preview {
  padding: 20px;
  min-height: 400px;
  height: auto;
  overflow: visible;

  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */

  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
}

.preview-sidebar {
  background: rgba(7, 15, 35, 0.9);
  border-radius: 8px;
  padding: 20px;
  min-height: 350px;
  border: 1px solid rgba(164, 244, 186, 0.2);
}

.preview-logo {
  display: flex;
  align-items: center;
  gap: 10px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(0, 234, 255, 0.2);
  margin-bottom: 20px;

  i {
    color: #00eaff;
    font-size: 20px;
  }

  span {
    color: rgba(255, 255, 255, 0.9);
    font-weight: 600;
    font-size: 16px;
  }
}

.preview-menu {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-menu-item {
  margin-bottom: 4px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 6px;
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.1);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(164, 244, 186, 0.1);
    border-color: rgba(0, 234, 255, 0.3);
  }

  .preview-icon {
    color: #00eaff;
    font-size: 16px;
    width: 16px;
  }

  .preview-text {
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
  }
}

.preview-submenu {
  .preview-parent {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    border-radius: 6px;
    background: rgba(164, 244, 186, 0.08);
    border: 1px solid rgba(164, 244, 186, 0.15);
    margin-bottom: 8px;
    cursor: pointer;

    .preview-icon {
      color: #00eaff;
      font-size: 16px;
      width: 16px;
    }

    .preview-text {
      color: rgba(255, 255, 255, 0.9);
      font-weight: 600;
      flex: 1;
    }

    .preview-arrow {
      color: rgba(255, 255, 255, 0.6);
      font-size: 12px;
    }
  }

  .preview-children {
    margin-left: 20px;
    padding-left: 16px;
    border-left: 2px solid rgba(0, 234, 255, 0.3);

    .preview-child {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 12px;
      border-radius: 4px;
      background: rgba(164, 244, 186, 0.03);
      border: 1px solid rgba(164, 244, 186, 0.08);
      margin-bottom: 4px;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(164, 244, 186, 0.08);
        border-color: rgba(0, 234, 255, 0.2);
      }

      .preview-child-icon {
        color: #00eaff;
        font-size: 14px;
        width: 14px;
      }

      .preview-child-text {
        color: rgba(255, 255, 255, 0.8);
        font-size: 14px;
      }
    }
  }
}



/* 菜单列表 */
.menu-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.menu-item-card {
  padding: 20px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow:
      0 12px 40px rgba(0, 0, 0, 0.4),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
  }
}

.menu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.menu-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.menu-icon {
  color: #00eaff;
  font-size: 18px;
  width: 20px;
  text-align: center;
}

.menu-name {
  color: rgba(255, 255, 255, 0.9);
  font-size: 1.1em;
  font-weight: 600;
}

.menu-path {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.9em;
  font-family: 'Courier New', monospace;
  background: rgba(0, 0, 0, 0.2);
  padding: 4px 8px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.menu-description {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9em;
  margin-bottom: 12px;
}

/* 子菜单 */
.menu-children {
  margin-top: 16px;
  padding-left: 20px;
  border-left: 3px solid rgba(0, 234, 255, 0.3);
}

.children-header {
  color: #00eaff;
  font-size: 0.9em;
  font-weight: 600;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.child-menu {
  background: rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(164, 244, 186, 0.1);
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.child-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.child-icon {
  color: #00eaff;
  font-size: 14px;
  width: 16px;
}

.child-name {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.child-path {
  color: rgba(255, 255, 255, 0.5);
  font-size: 0.8em;
  font-family: 'Courier New', monospace;
  margin-left: 8px;
}



/* 图标网格 */
.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 8px;
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 6px;
  background: rgba(164, 244, 186, 0.05);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(164, 244, 186, 0.1);
    border-color: rgba(0, 234, 255, 0.5);
    transform: translateY(-2px);
  }
}

.icon-preview {
  font-size: 24px;
  color: #00eaff;
  margin-bottom: 8px;
}

.icon-name {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
  word-break: break-all;
  line-height: 1.2;
}

/* 按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  box-shadow:
    0 2px 8px rgba(164, 244, 186, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    transform: translateY(-1px) !important;
    box-shadow:
      0 4px 12px rgba(164, 244, 186, 0.2),
      inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }

  /* 测试连接按钮 - 橙色 */
  &.test-button {
    background: rgba(255, 165, 0, 0.2) !important;
    border-color: rgba(255, 165, 0, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(255, 165, 0, 0.3) !important;
      border-color: rgba(255, 165, 0, 0.6) !important;
    }

    i {
      color: #ffa500 !important;
    }
  }

  /* 刷新配置按钮 - 紫色 */
  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  /* 添加配置按钮 - 绿色 */
  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  /* 创建菜单按钮 - 蓝色 */
  &.create-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }
}

/* 操作按钮样式 */
.action-glass-button {
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;
  font-size: 12px !important;
  min-width: 60px !important;
  background: rgba(0, 234, 255, 0.15) !important;
  border: 1px solid rgba(0, 234, 255, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  box-shadow:
    0 2px 8px rgba(0, 234, 255, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  &:hover {
    background: rgba(0, 234, 255, 0.25) !important;
    border-color: rgba(0, 234, 255, 0.5) !important;
    color: #ffffff !important;
    transform: translateY(-1px) !important;
    box-shadow:
      0 4px 12px rgba(0, 234, 255, 0.2),
      inset 0 1px 0 rgba(255, 255, 255, 0.2) !important;
  }

  i {
    margin-right: 4px !important;
    color: #00eaff !important;
  }
}

/* 对话框样式 */
:deep(.el-dialog) {
  background: rgba(164, 244, 186, 0.1) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 12px !important;
  backdrop-filter: blur(20px) !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-dialog__header) {
  background: rgba(164, 244, 186, 0.05) !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 12px 12px 0 0 !important;
  padding: 20px !important;
}

:deep(.el-dialog__title) {
  color: #00eaff !important;
  font-weight: bold !important;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
  font-size: 1.2em !important;
}

:deep(.el-dialog__body) {
  background: rgba(164, 244, 186, 0.05) !important;
  padding: 30px !important;
  color: rgba(255, 255, 255, 0.9) !important;
}

/* 标签样式 */
:deep(.el-tag) {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 4px !important;

  &.el-tag--success {
    background: rgba(0, 234, 255, 0.2) !important;
    border-color: rgba(0, 234, 255, 0.4) !important;
    color: #ffffff !important;
  }
}

/* 表单样式 */
:deep(.create-form) {
  .el-form-item__label {
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 500 !important;
  }

  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 6px !important;
    box-shadow: none !important;

    &:hover {
      border-color: rgba(164, 244, 186, 0.5) !important;
    }

    &.is-focus {
      border-color: #00eaff !important;
      box-shadow: 0 0 5px rgba(0, 234, 255, 0.3) !important;
    }
  }

  .el-input__inner {
    background: transparent !important;
    border: none !important;
    color: rgba(255, 255, 255, 0.9) !important;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }

  .el-textarea__inner {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    border-radius: 6px !important;

    &:focus {
      border-color: #00eaff !important;
      box-shadow: 0 0 5px rgba(0, 234, 255, 0.3) !important;
    }

    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }
}

/* 图标选择器样式 */
.icon-selector {
  .selected-icon {
    color: #00eaff;
    font-size: 16px;
  }
}

.icon-search {
  margin-bottom: 16px;
}

.icon-item {
  cursor: pointer;

  &.active {
    background: rgba(0, 234, 255, 0.2) !important;
    border-color: #00eaff !important;

    .icon-preview {
      color: #00eaff !important;
    }
  }
}

/* 预览信息样式 */
.preview-info {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 12px;

  .preview-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    label {
      color: rgba(255, 255, 255, 0.8);
      width: 80px;
      flex-shrink: 0;
      font-size: 12px;
    }

    code {
      background: rgba(0, 234, 255, 0.1);
      color: #00eaff;
      padding: 2px 6px;
      border-radius: 3px;
      font-size: 12px;
      font-family: 'Courier New', monospace;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* Element Plus 树形组件样式覆盖 */
:deep(.el-tree) {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;

  .el-tree-node {
    margin-bottom: 12px !important;

    .el-tree-node__content {
      background: transparent !important;
      border: none !important;
      padding: 0 !important;
      height: auto !important;
      line-height: normal !important;

      &:hover {
        background: transparent !important;
      }

      &:focus {
        background: transparent !important;
      }
    }

    .el-tree-node__expand-icon {
      color: #00eaff !important;
      font-size: 14px !important;
      margin-right: 8px !important;

      &.is-leaf {
        color: transparent !important;
      }
    }

    .el-tree-node__label {
      display: none !important; /* 隐藏默认标签，使用自定义内容 */
    }

    /* 子节点缩进 */
    .el-tree-node__children {
      padding-left: 0 !important;

      .el-tree-node {
        .tree-node {
          margin-left: 0 !important;
        }
      }
    }
  }

  .el-tree-node.is-expanded > .el-tree-node__content {
    background: transparent !important;
  }

  .el-tree-node.is-current > .el-tree-node__content {
    background: transparent !important;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-layout {
    flex-direction: column;
    gap: 20px;
  }

  .left-panel,
  .right-panel {
    min-width: auto;
  }

  .menu-preview {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }

  .stats-section {
    justify-content: center;
    flex-wrap: wrap;
  }

  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
}

/* 表单提示 */
.form-tip {
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(0, 234, 255, 0.1);
  border: 1px solid rgba(0, 234, 255, 0.2);
  border-radius: 4px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 6px;

  i {
    color: #00eaff;
  }
}
</style>
